package org.mcjug.locationmailer.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import oauth.signpost.OAuth;

import org.mcjug.locationmailer.R;
import org.mcjug.locationmailer.model.Email;
import org.mcjug.locationmailer.model.StatusMessage;
import org.mcjug.locationmailer.oauth.xauth.XoauthAuthenticator;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.sun.mail.smtp.SMTPTransport;

public class EmailUtil {
	public static final String EMAIL_ADDRESS = "emailAddress";
    public static final String EMAIL_ADDRESS_STATE = "emailAddressState";	

    public static List<String> getRecipients(SharedPreferences prefs) {
	    List<String> emailAddressList = getCSVList(prefs, EMAIL_ADDRESS);
	    List<String> emailAddressStateList = getCSVList(prefs, EMAIL_ADDRESS_STATE);
	    if (emailAddressList == null || emailAddressStateList == null) {
	    	return null;
	    }
	    
	    List<String> recipients = new ArrayList<String>();
	    boolean isActive;
	    for (int i = 0; i < emailAddressList.size(); i++) {
	    	isActive = Boolean.parseBoolean(emailAddressStateList.get(i));
	    	if (isActive) {
	    		recipients.add(emailAddressList.get(i));
	    	}
	    }
        return recipients;
	}
	
	public static List<String> getCSVList(SharedPreferences prefs, String key) {
		List<String> list = new ArrayList<String>();
		String str = prefs.getString(key, null);
		if (str != null) {
			list = new ArrayList<String>(Arrays.asList(str.split(",")));
		}
		return list;
	}
	
	public static String getCSVString(List<String> list, String delimiter) {
	    if (list == null || list.isEmpty())
		    return "";
	 
	    StringBuilder strBuilder = new StringBuilder();
	    for (String str : list) {
	    	strBuilder.append(str + delimiter);
	    }
	    strBuilder.delete(strBuilder.length()-delimiter.length(), strBuilder.length());
	 
	    return strBuilder.toString();
	}	
	
	public static void sendEmail(StatusMessage statusMessage, Context context) {
		try {
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			String oauthToken = prefs.getString(OAuth.OAUTH_TOKEN, null);
			String oauthTokenSecret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, null);
			
			if (TextUtils.isEmpty(oauthToken) || TextUtils.isEmpty(oauthTokenSecret)) {
			    statusMessage.setMessage(context.getString(R.string.msgGmailOAuthNoTokens));
				return;
			}
			
			Email email = getEmail(statusMessage, context);		
			SMTPTransport smtpTransport = XoauthAuthenticator.connectToSmtp(
					"smtp.googlemail.com", 587, email.getSender(), oauthToken,
					oauthTokenSecret, XoauthAuthenticator.getAnonymousConsumer(), true);
			
			Properties props = System.getProperties();
			props.put("mail.smtps.host", "smtp.gmail.com");
			props.put("mail.smtps.auth", "true");			
			Session session = Session.getInstance(props, null);
			
			List<String> recipients = email.getRecipients();
			for (String recipient: recipients) {
				Message msg = new MimeMessage(session);
				msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
				msg.setFrom(new InternetAddress(email.getSender()));
				msg.setSubject(email.getSubject());
				msg.setText(email.getBody());
				msg.setHeader("X-Mailer", "Android program");
				msg.setSentDate(new Date());
				smtpTransport.sendMessage(msg, msg.getAllRecipients());
			}
			
		} catch (Exception e) {
			statusMessage.setMessage(context.getString(R.string.msgEmailError));
		} 
	}
	
	public static Email getEmail(StatusMessage statusMessage, Context context) {
	    Email email = new Email();
	    
	    // Sender/Subject
	    email.setSender(context.getString(R.string.emailSender));
	    email.setSubject(context.getString(R.string.emailSubject));
	    
	   	// Recipients
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
	    email.setRecipients(getRecipients(prefs));

	    // Email Body
	    StringBuilder sb = new StringBuilder();
	    sb.append(context.getString(R.string.location) + "\n");
        sb.append("\t" + statusMessage.getAddress() + "\n");
        
        // Location
        Location location = statusMessage.getLocation();
        String locationStr;
        if (location == null) {
        	locationStr = context.getString(R.string.msgNoLocation);
        } else {
			locationStr = String.format(context.getString(R.string.latitudeFormatted)
					+ "\t" + context.getString(R.string.longitudeFormatted), location
					.getLatitude(), location.getLongitude());
        }        
   	    sb.append("\t" + locationStr);
   	    
    	email.setBody(sb.toString());    	
 	    
        return email;
	};	
}
